package org.ehe.system.service.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.ehe.common.core.utils.DateUtils;
import org.ehe.common.core.utils.SFTPUtil;
import org.ehe.common.satoken.utils.LoginHelper;
import org.ehe.system.service.ISysFtpService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 文件上传ServiceImpl
 * @author :zhangnn
 * @className :ISysFtpServiceImpl
 * @description: TODO
 * @date 2025-09-19 09:31:15
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class SysFtpServiceImpl implements ISysFtpService {
    @Value("${sftp.sftpUrl}")
    private String  sftpUrl;

    @Value("${sftp.sftpPort}")
    private int  sftpPort;

    @Value("${sftp.sftpUsername}")
    private String  sftpUsername;

    @Value("${sftp.sftpPassword}")
    private String  sftpPassword;

    @Value("${sftp.sftpBasePath}")
    private String sftpBasePath;

    @Value("${sftp.sftpImagePath}")
    private String sftpImagePath;

    @Value("${sftp.sftpFilePath}")
    private String sftpFilePath;

    @Override
    public Map<String, Object> uploadFile(String fileNameOld, InputStream ins, boolean nameTag) {
        Map<String, Object> result = new HashMap<>(4);
        SFTPUtil sftp = null;
        try {
            /* 1. 后缀 & 子目录选择 */
            String suffix = fileNameOld.substring(fileNameOld.lastIndexOf(".") + 1).toLowerCase();
            String filePath = ArrayUtils.contains(new String[]{"jpg", "jpeg", "png", "gif"}, suffix)
                ? sftpImagePath : sftpFilePath;

            String userName = LoginHelper.getUsername();
            String datePath = DateUtils.getDate("yyyyMMdd");
            String fileNamePath = filePath + "/" + userName + "/" + datePath + "/";

            /* 2. 组装远端目录：images/2025/09/19/  或 files/2025/09/19/ */
//            String fileNamePath = filePath
//                + "/" + DateUtils.getDate("yyyy") + "/"
//                + DateUtils.getDate("MM") + "/" + DateUtils.getDate("dd") + "/";

            /* 3. 新文件名 */
            long timestamp = System.currentTimeMillis();
            int randomNum = new Random().nextInt(1000); // 生成0-999的随机数
            String newName = timestamp + "_" + randomNum + "." + suffix;
//            String newName = (nameTag ? fileNameOld.substring(0, fileNameOld.lastIndexOf(".")) + "_" : "")
//                + System.currentTimeMillis() + "." + suffix;

            /* 4. 登录 + 上传（自动建目录） */
            sftp = new SFTPUtil(sftpUsername, sftpPassword, sftpUrl, sftpPort);
            sftp.login();
            log.info("sftpBasePath {}", sftpBasePath);
            log.info("fileNamePath {}", fileNamePath);
            log.info("fileName {}", newName);
            sftp.upload(sftpBasePath, fileNamePath, newName, ins);

            /* 5. 封装返回（可访问的完整 URL） */
            String accessUrl = sftpBasePath + "/" + fileNamePath + newName;
            result.put("code",200);
            result.put("url", accessUrl);
            result.put("suffix", suffix);
            result.put("fileName", newName);
            result.put("relativePath", fileNamePath.replace("sftp","") + newName);
        } catch (Exception e) {
            log.error("文件上传异常", e);
            result.put("error", e.getMessage());
        } finally {
            if (sftp != null) sftp.logout();
            try {
                ins.close();
            } catch (IOException ignored) {

            } // 关流
        }
        return result;
    }

}
